package com.hairy.nipples.hardware.accelerometer;

import java.util.Date;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.hairy.nipples.hardware.accelerometer.PhoneMovementDetector.PhoneMovementBasedActionsCallback;
import com.hairy.nipples.util.AccelerationUtil;

public class AccelerometerListener implements SensorEventListener {
	private Long startTime;

	private PhoneMovementBasedActionsCallback callback;

	private SensorManager sensorManager;

	boolean invoked = false;

	boolean isMoving;

	public AccelerometerListener(PhoneMovementBasedActionsCallback callback,
			SensorManager sensorManager) {
		this.callback = callback;
		this.sensorManager = sensorManager;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (!invoked) {
			isMoving |= !AccelerationUtil.isStandingStill(event.values);

			if (startTime == null) {
				startTime = new Date().getTime();
			}

			long now = new Date().getTime();

			// Detecting movements in 5 seconds
			if (now - startTime > 5000) {
				if (isMoving) {
					callback.doActionsWhenMoving();
				} else {
					callback.doActionsWhenStill();
				}

				// Unregistering sensor listener.
				sensorManager.unregisterListener(this);

				invoked = true;
			}
		}
	}
}